package com.balance.anole.client.retail.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

import com.balance.anole.admin.to.ShopTO;
import com.balance.anole.business.service.BusinessService;
import com.balance.anole.business.to.BusinessDateTO;
import com.balance.anole.client.common.service.CommonService;
import com.balance.anole.client.retail.service.RetailService;
import com.balance.anole.client.retail.service.UploadDownloadService;
import com.balance.anole.client.retail.view.RetailView;
import com.balance.anole.erp.security.SessionManager;
import com.balance.anole.erp.util.ServicesCenter;
import com.balance.anole.upload.service.UploadService;
import com.balance.anole.utils.DateUtil;

public class UploadAction extends Action {
	private static final CommonService cs = ServicesCenter.getServicesCenter()
			.getService(CommonService.class);

	private static final RetailService rs = ServicesCenter.getServicesCenter()
	.getService(RetailService.class);

	private static final UploadService us = ServicesCenter.getServicesCenter()
	.getService(UploadService.class);

	private static final BusinessService bs = ServicesCenter.getServicesCenter()
	.getService(BusinessService.class);

	public UploadAction(){
		super();
		setText("上传数据");
		this.setId(UploadAction.class.getName());
	}

	@Override
	public void run() {
		Set<Date> datesToUpload = new HashSet<Date>();
		Set<Date> failureDates = null;
		final BusinessDateTO businessDate = cs.getBusinessDate();
		String currentBizDateStr = "";
		if (businessDate == null){
			MessageDialog.openError(Display.getDefault()
					.getActiveShell(), "错误", "日期错误，请检查数据库");
			return;
		} else{
			Date currentBizDate = businessDate.getBusinessDate();
			currentBizDateStr = DateUtil.format(currentBizDate, "yyyy-MMM-dd");
			datesToUpload.add(currentBizDate);
		}

		try{
			failureDates = bs.getUploadFailedBusinessDates(SessionManager.getInstance().getLoginUser().getStaffInfo().getStaffOwner());
		}catch(Exception e){
			boolean confirmed = MessageDialog.openConfirm(Display.getDefault()
					.getActiveShell(), "错误", "服务器连接错误！\n\n " + e.getMessage() + "\n\n 继续锁定当天业务吗？");
			if(confirmed){
				businessDate.setLocked(true);
				cs.insertOrUpdateBusinessDate(businessDate);
				MessageDialog.openInformation(Display.getDefault()
						.getActiveShell(), "提示", "系统业务日期锁定，收银功能在下个工作日解锁。");
				IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
				window.getActivePage().hideView(window.getActivePage().findView(RetailView.ID));
			}
			return;
		}
		StringBuffer confirmMsg = new StringBuffer();
		if(failureDates != null){
			for(Date date : failureDates){
				confirmMsg.append(DateUtil.format(date, "yyyy-MMM-dd")).append("(失败再次上传)").append("\n");
				datesToUpload.add(date);
			}
		}
		confirmMsg.append(currentBizDateStr).append("(当天数据上传)").append("\n");
		confirmMsg.append("确定上传这些数据吗?");
		boolean upload = MessageDialog.openConfirm(Display.getDefault()
				.getActiveShell(), "确认", confirmMsg.toString());

		if (upload) {
			List<BusinessDateTO> uploadDateTO = new ArrayList<BusinessDateTO>();
			for(Date date : datesToUpload){
				uploadDateTO.add(cs.getBusinessDateByCurrentBusinessDate(date));
			}

			JobChangeAdapter jca = new JobChangeAdapter(){
				private String status = "";
				@Override
				public void done(IJobChangeEvent event) {
					super.done(event);
					final UploadJob job = (UploadJob) event.getJob();
					final boolean isSuccess = job.isSuccess();
					if(isSuccess){
						status = "成功";
					}else{
						status = "失败";
					}
					Display.getDefault().asyncExec(new Runnable(){
						@Override
						public void run() {
							MessageDialog.openInformation(new Shell(), status, job.getMessage());

							if(isSuccess){
								IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
								window.getActivePage().hideView(window.getActivePage().findView(RetailView.ID));
							}
						}

					});
				}

			};

			Job job = new UploadJob("上传数据", uploadDateTO);
			job.setUser(true);
			job.addJobChangeListener(jca);
			job.schedule();
		}
	}

	public class UploadJob extends Job{

		private List<BusinessDateTO> businessDates = null;

		private boolean success = true;

		private String message = "";

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public UploadJob(String name, List<BusinessDateTO> businessDates) {
			super(name);
			this.businessDates = businessDates;
		}

		@Override
		protected IStatus run(IProgressMonitor monitor) {

	    	monitor.beginTask("上传 ...", 100);

			monitor.subTask("从数据库导出数据 ...");
			// do the job.
			//TODO: loading in batch.
			/*List<ShopReceiptTO> data = rs.getShopReceipts4Upload(cs.getShop(SessionManager.getInstance().getLoginUser().getStaffInfo().getStaffOwner()), businessDate, DataConstants.UPLOAD_FETCH_SIZE);
			int dataSize = 0;
			if(data != null){
				dataSize = data.size();
				//reset ID.
				for (ShopReceiptTO shopReceiptTO : data) {
					shopReceiptTO.setId(null);
					Set<ShopPaymentTO> payment = shopReceiptTO.getPaymentList();
					if(payment != null){
						for (ShopPaymentTO shopPaymentTO : payment) {
							shopPaymentTO.setId(null);
						}
					}

					Set<ShopReceiptPdtItemTO> items = shopReceiptTO.getPdtItemSoldList();
					if(items != null){
						for (ShopReceiptPdtItemTO shopReceiptPdtItemTO : items) {
							shopReceiptPdtItemTO.setId(null);
						}
					}
				}
			}

			monitor.worked(50);
			monitor.subTask(dataSize + " have(has) been found.");

			if(data != null && dataSize > 0){
				monitor.subTask("Uploading to server ...");
				us.uploadShopReceipts(data);
				monitor.worked(50);
			}*/

			UploadDownloadService uds = ServicesCenter.getServicesCenter().getService(UploadDownloadService.class);

			ShopTO shop = cs.getShop(SessionManager.getInstance().getLoginUser().getStaffInfo().getStaffOwner());
			String agentId = shop.getShop().getAgentId();
			StringBuffer msg = new StringBuffer();
			if(businessDates != null){
				for(BusinessDateTO businessDate : businessDates){
					msg.append(DateUtil.format(businessDate.getBusinessDate(), "yyyy-MMM-dd")).append(": ");
					try{
						boolean success = true;
						success = uds.upload(businessDate, agentId);
						if(!success){
							msg.append("导出异常");
							setSuccess(false);
						}else{
							msg.append("上传成功");
							setSuccess(isSuccess());
						}
					}catch(Exception e){
						msg.append(e.getMessage());
						setSuccess(false);
					}
					msg.append("\n");
				}
			}

			//if upload successfully, then lock current business date.
			if(isSuccess()){
				BusinessDateTO businessDate = cs.getBusinessDate();
				businessDate.setLocked(true);
				cs.insertOrUpdateBusinessDate(businessDate);
				msg.append("上传数据全部成功，系统业务日期锁定，收银功能在下个工作日解锁。");
			}

			setMessage(msg.toString());
			monitor.done();
	        return Status.OK_STATUS;

		}

	}


}
